{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 结果为0\n",
    "## 没有执行io操作的协诚，会顺序执行\n",
    "\n",
    "import asyncio\n",
    "\n",
    "total = 0\n",
    "\n",
    "async def add():\n",
    "    global total\n",
    "    for i in range(1000000):\n",
    "        total += 1\n",
    "\n",
    "async def desc():\n",
    "    global total\n",
    "    for i in range(1000000):\n",
    "        total -= 1\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    tasks = [add(), desc()]\n",
    "    loop = asyncio.get_event_loop()\n",
    "    loop.run_until_complete(asyncio.wait(tasks))\n",
    "    print(total)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## 可以采用asyncio队列限流\n",
    "## 如果没有长度限制，则可以直接使用全局数组\n",
    "## queue = []\n",
    "\n",
    "import asyncio\n",
    "from asyncio import Lock, Queue\n",
    "cache = {}\n",
    "lock = Lock()\n",
    "queue = Queue\n",
    "\n",
    "\n",
    "async def get_stuff(url):\n",
    "    async with lock:\n",
    "        if url in cache:\n",
    "            return cache[url]\n",
    "        stuff = await aiohttp.request('GET', url)\n",
    "        cache[url] = stuff\n",
    "        return stuff\n",
    "\n",
    "\n",
    "async def parse_stuff():\n",
    "    stuff = await get_stuff()\n",
    "    # do some parsing\n",
    "\n",
    "async def use_stuff():\n",
    "    stuff = await get_stuff()\n",
    "    # use stuff to do something interesting\n",
    "\n",
    "\n",
    "tasks = [parse_stuff(),use_stuff()]\n",
    "loop = asyncio.get_event_loop()\n",
    "loop.run_until_complete(asyncio.wait(tasks))\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
